package com.yk.server;

import com.yk.decode.RpcDecoder;
import com.yk.decode.RpcEncoder;
import com.yk.pojo.ReqMessage;
import com.yk.pojo.RespMessage;
import com.yk.serverhandler.MessageRecvHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

/**
 * Created by dingkl on 2017/7/27.
 */
public class RPCServer {

    public void bind(int port){
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup,workGroup);
        serverBootstrap.channel(NioServerSocketChannel.class);
        serverBootstrap.option(ChannelOption.SO_BACKLOG,128);
        serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                //java序列化
                //socketChannel.pipeline().addLast(new ObjectDecoder(1024*1024, ClassResolvers.weakCachingResolver(this.getClass().getClassLoader())));
                //socketChannel.pipeline().addLast(new ObjectEncoder());

                socketChannel.pipeline().addLast(new RpcDecoder(ReqMessage.class));
                socketChannel.pipeline().addLast(new RpcEncoder(RespMessage.class));
                //接收处理
                socketChannel.pipeline().addLast(new MessageRecvHandler());
            }
        });
        try {
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            System.out.println("启动服务:"+port);
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}
